package cc.booku.owlbox.Idiom;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import cc.booku.owlbox.ArtDesign.SystemUtil;
import cc.booku.owlbox.FileOperations.FileoOperations;
import cc.booku.owlbox.R;
import cc.booku.owlbox.RsaUtil.Decrypt;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


public class IdiomActivity extends AppCompatActivity {


    private List<IdiomClass> Idiomclasslist = new ArrayList<IdiomClass>();
    //    private SearchView searchView;
    private String ProfilePath = Environment.getExternalStorageDirectory() + File.separator + "OwlDatabase" + File.separator + "Profile.txt";
    private EditText et_text;
    private Button bt_search;
    private ImageView iv_back;

    public String SEARCH_DATA = null;
    private GridView lv_main_list2;//,lv_carrouse;
    private idiomAdapter idiomAdapterSHOW;

    private ClipboardManager cm;
    private ClipData mClipData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_idiom);
        //状态栏颜色
        SystemUtil.setStatusBarColor(this, Color.parseColor("#448aca"));
        iv_back = (ImageView) findViewById(R.id.iv_back);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


        lv_main_list2 = (GridView) findViewById(R.id.lv_main_list2);

        // 2. 绑定视图
        // setContentView(R.layout.activity_search);

        // 3. 绑定组件
        et_text = (EditText) findViewById(R.id.et_text);
        bt_search = (Button) findViewById(R.id.bt_search);

        bt_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String str = et_text.getText().toString();
                PinYinUtil upinyin = new PinYinUtil();

                if (str.matches("[\u4E00-\u9FA5]+")) {

                    SEARCH_DATA = upinyin.getPingYin(str);


                    Message msg = new Message();
                    msg.what = 7;
                    Bundle bundle = new Bundle();
                    bundle.putString("searchstring", SEARCH_DATA);  //往Bundle中存放数据
                    msg.setData(bundle);//mes利用Bundle传递数据
                    handler.sendMessage(msg);//用activity中的handler发送消息

                } else {
                    SEARCH_DATA = str;
                    //从服务器获得最新版本 load_version
                    Message msg = new Message();
                    msg.what = 7;
                    Bundle bundle = new Bundle();
                    bundle.putString("searchstring", str);  //往Bundle中存放数据
                    msg.setData(bundle);//mes利用Bundle传递数据
                    handler.sendMessage(msg);//用activity中的handler发送消息

                }

            }
        });


//        // 4. 设置点击键盘上的搜索按键后的操作（通过回调接口）
//        // 参数 = 搜索框输入的内容
//        searchView.setOnClickSearch(new ICallBack() {
//            @Override
//            public void SearchAciton(String string) {
//                System.out.println("我收到了" + string);
//
//
//                PinYinUtil upinyin = new PinYinUtil();
//
//                if (string.matches("[\u4E00-\u9FA5]+")) {
//
//                    SEARCH_DATA = upinyin.getPingYin(string);
//
//
//                    Message msg = new Message();
//                    msg.what = 7;
//                    Bundle bundle = new Bundle();
//                    bundle.putString("searchstring", SEARCH_DATA);  //往Bundle中存放数据
//                    msg.setData(bundle);//mes利用Bundle传递数据
//                    handler.sendMessage(msg);//用activity中的handler发送消息
//
//                } else {
//                    SEARCH_DATA = string;
//                    //从服务器获得最新版本 load_version
//                    Message msg = new Message();
//                    msg.what = 7;
//                    Bundle bundle = new Bundle();
//                    bundle.putString("searchstring", string);  //往Bundle中存放数据
//                    msg.setData(bundle);//mes利用Bundle传递数据
//                    handler.sendMessage(msg);//用activity中的handler发送消息
//
//                }
//
//
//                //Log.d("11111", "onResponse:cityBean " + upinyin.getPingYin(string));
//
//
//            }
//        });

    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case 7:
                    //获取最新app信息
                    String searchstring = msg.getData().getString("searchstring");//接受msg传递过来的参数
                    Idiomclasslist.clear();


                    String ConfigFiles_json = FileoOperations.readAssetsTxt(IdiomActivity.this, "TxtData/ConfigFiles");
                    JSONObject objsd = JSONObject.parseObject(ConfigFiles_json);
                    String ciphertext = objsd.getString("ADDRESSCIPHER");//地址密文
                    String DecryptionAddress = Decrypt.RsaDecrypt(IdiomActivity.this, ciphertext);
                    String idiom = objsd.getString("IDIOM");//成语接龙

                    tosearchdata_json(DecryptionAddress + idiom + searchstring);
//                    String ProfileStr = FileoOperations.readFromSDFile(IdiomActivity.this, ProfilePath);
//                    //读取配置文件信息
//                    try {
//                        JSONObject obj = JSONObject.parseObject(ProfileStr);
//                        String result = obj.getString("成语接龙接口");
//                        String ciphertext = obj.getString("地址密文");
//                        String res = Decrypt.RsaDecrypt(IdiomActivity.this, ciphertext);
//
//                        searchstring = res + result + searchstring;
//                        Log.d("str9", "str9======" + searchstring);
//                        tosearchdata_json(searchstring);
//                    } catch (Exception e) {
////异常处理
//                    }
                    break;
                case 8:

                    RecommendListData((ArrayList<IdiomClass>) Idiomclasslist);
                    break;
            }
        }
    };


    private IdiomClass idiomClasslist;

    public String tosearchdata_json(String Surl_file) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        Request.Builder requestBuilder = new Request.Builder().url(Surl_file);
        //可以省略，默认是GET请求
        requestBuilder.method("GET", null);
        Request request = requestBuilder.build();
        Call mcall = mOkHttpClient.newCall(request);
        mcall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("1111", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsoninfo = response.body().string();

                // CityBean cityBean = JSON.parseObject(json, TestBean.class);
                // Log.d(TAG, "onResponse:cityBean " + cityBean);
                //通过句柄发送json

                //[[{"vod_id":"13442","vod_name":"奴隷倶楽部へ売られた女 神宮寺ナオ","vod_class":"有码视频","vod_pic":"https:\/\/img.dadiziyuan.net\/upload\/vod\/2018-12-29\/201812291546066673.jpg","vod_play_url":"在线播放$https:\/\/dadi-bo.com\/share\/d6UbsOhDdXesoJN0$$$在线播放$https:\/\/dadi-bo.com\/20181227\/VAYN7v2L\/index.m3u8"}]]
                // String jsonstr1 = jsoninfo.replace("[{", "{");
                // String jsonstr2 = jsonstr1.replace("}]", "}");
                //String jsonstr3 = jsoninfo.replace("$$$在线播放$", "|");


                ByteArrayInputStream stream = new ByteArrayInputStream(jsoninfo.getBytes());
                StringBuffer stringBuffer = new StringBuffer();
                String str = null;
                BufferedReader br = new BufferedReader(new InputStreamReader(stream));
                while ((str = br.readLine()) != null) {
                    stringBuffer.append(str);
                }
                //03.使用fastJson解析Json、
                List<IdiomClass> pidiomClass = JSON.parseArray(stringBuffer.toString(), IdiomClass.class);
                for (IdiomClass pp : pidiomClass) {
                    idiomClasslist = new IdiomClass();
                    String word = pp.getWord();
                    String pinyin = pp.getPinyin();
                    String explanation = pp.getExplanation();
                    String example = pp.getExample();
                    String derivation = pp.getDerivation();


                    PinYinUtil upinyin = new PinYinUtil();

                    String jsonstr3[] = upinyin.getPingYin(word).split(" ");

                    Log.i("test======", "jsonstr3jsonstr3jsonstr3====" + jsonstr3[0]);


                    idiomClasslist.setPinyin(pinyin);
                    idiomClasslist.setWord(word);
                    idiomClasslist.setExplanation(explanation);
                    idiomClasslist.setExample(example);
                    idiomClasslist.setDerivation(derivation);


                    //pfilmclass.setParea(carea);
                    //将结果添加到对象集合中

//                    if (SEARCH_DATA.equals(jsonstr3[0])) {
//
//                    } else {
//
//                    }

                    if (SEARCH_DATA.indexOf(jsonstr3[0]) != -1) {
                        Idiomclasslist.add(idiomClasslist);
                    } else {
                        Log.i("test======", "jsonstr3jsonstr3jsonstr3====" + jsonstr3[0]);
                        Log.i("test======", "SEARCH_DATASEARCH_DATASEARCH_DATA====" + SEARCH_DATA);
                    }


                }
                Message msg = new Message();
                msg.what = 8;
                handler.sendMessage(msg);//用activity中的handler发送消息

            }
        });
        return null;
    }


    public void RecommendListData(ArrayList<IdiomClass> filmclassList) {

        idiomAdapterSHOW = new idiomAdapter(R.layout.idiom_item, this, filmclassList);

        lv_main_list2.setAdapter(idiomAdapterSHOW);
        lv_main_list2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                //跳转提示
                // Toast.makeText(MainActivity.this, "Click item" + i, Toast.LENGTH_SHORT).show();
                final TextView word = (TextView) view.findViewById(R.id.word);
                final TextView pinyin = (TextView) view.findViewById(R.id.pinyin);
                final TextView explanation = (TextView) view.findViewById(R.id.explanation);
                final TextView example = (TextView) view.findViewById(R.id.example);
                final TextView derivation = (TextView) view.findViewById(R.id.derivation);


                String word1 = word.getText().toString();
                //shareText("成语红包", "答案", word1);
// TODO Auto-generated method stub
//获取剪贴板管理器：
                cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
                mClipData = ClipData.newPlainText("Label", word1);
// 将ClipData内容放到系统剪贴板里。
                cm.setPrimaryClip(mClipData);
                Toast.makeText(IdiomActivity.this, "“" + word1 + "”" + "复制成功", Toast.LENGTH_SHORT).show();

            }
        });

    }


    /**
     * 分享文字内容
     *
     * @param dlgTitle 分享对话框标题
     * @param subject  主题
     * @param content  分享内容（文字）
     */
    private void shareText(String dlgTitle, String subject, String content) {
        if (content == null || "".equals(content)) {
            return;
        }
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        if (subject != null && !"".equals(subject)) {
            intent.putExtra(Intent.EXTRA_SUBJECT, subject);
        }

        intent.putExtra(Intent.EXTRA_TEXT, content);

        // 设置弹出框标题
        if (dlgTitle != null && !"".equals(dlgTitle)) { // 自定义标题
            startActivity(Intent.createChooser(intent, dlgTitle));
        } else { // 系统默认标题
            startActivity(intent);
        }
    }

    //自己写个适配器类
    class idiomAdapter extends BaseAdapter implements ListAdapter {

        private LayoutInflater mInflater;
        private ArrayList mData = new ArrayList();

        private ArrayList<IdiomClass> Idiomclasslist;
        private int id;
        private Context context;
        private LayoutInflater inflater;

        public idiomAdapter(int searchvideo_item, IdiomActivity videoListActivity, ArrayList<IdiomClass> Idiomclasslist) {
            this.Idiomclasslist = Idiomclasslist;
            this.context = videoListActivity;
            this.id = searchvideo_item;
            inflater = LayoutInflater.from(context);

        }

        //private ImageView image_url;

        @Override
        public int getCount() {
            return Idiomclasslist.size();
        }

        @Override
        public Object getItem(int i) {
            return Idiomclasslist.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @SuppressLint("WrongConstant")
        @Override

        public View getView(int i, View view, ViewGroup viewGroup) {

            TextView word = null;
            TextView pinyin = null;
            TextView explanation = null;
            TextView example = null;
            TextView derivation = null;


            idiomAdapter.ViewHolder viewHolder;
            if (view == null) {
                //view = LayoutInflater.from(getContext()).inflate(R.layout.searchvideo_item, viewGroup, false);
                view = inflater.inflate(id, null);
                //viewHolder = new ViewHolder();
                word = (TextView) view.findViewById(R.id.word);
                pinyin = (TextView) view.findViewById(R.id.pinyin);
                explanation = (TextView) view.findViewById(R.id.explanation);
                example = (TextView) view.findViewById(R.id.example);
                derivation = (TextView) view.findViewById(R.id.derivation);
                // view.setTag(viewHolder); // 将ViewHolder存储在View中
                view.setTag(new idiomAdapter.ViewHolder(word, pinyin, explanation, example, derivation));
            } else {
                // view = view;
                idiomAdapter.ViewHolder viewHolder1 = (idiomAdapter.ViewHolder) view.getTag(); // 重新获取ViewHolder
                word = viewHolder1.word;
                pinyin = viewHolder1.pinyin;
                explanation = viewHolder1.explanation;
                example = viewHolder1.example;
                derivation = viewHolder1.derivation;
            }
            IdiomClass idiomclass = (IdiomClass) Idiomclasslist.get(i); // 获取当前项的实例

            word.setText(idiomclass.getWord().toString());
            pinyin.setText(idiomclass.getPinyin().toString());
            explanation.setText(idiomclass.getExplanation().toString());
            example.setText(idiomclass.getExample().toString());
            derivation.setText(idiomclass.getDerivation().toString());
            // Imageload.showimagebyasynctask(image_url, filmclass.getPimg());

            return view;

        }


        private final class ViewHolder {
            TextView word = null;
            TextView pinyin = null;
            TextView explanation = null;
            TextView example = null;
            TextView derivation = null;


            public ViewHolder(TextView word, TextView pinyin, TextView explanation, TextView example, TextView derivation) {
                this.word = word;
                this.pinyin = pinyin;
                this.explanation = explanation;
                this.example = example;
                this.derivation = derivation;
            }

        }
    }


}
